package main.java.indi.zyj.interview;

public class SingletonController {

    //默认是第一次创建
    private static volatile boolean isCreate = false;

    //本类内部创建对象实例
    private static volatile SingletonController instance;

    //获取单例的方法
    public static SingletonController getSingleton() {
        if (null == instance) {
            synchronized (SingletonController.class) {
                if (null == instance) {
                    instance = new SingletonController();//若不加volatile，会产生指令重排序。原因是，可能先赋值地址值给instance，然后再创建对象
                }
            }
        }
        return instance;
    }

    /**
     * 构造方法私有化，外部不能new
     */
    private SingletonController() {
        if (isCreate) {
            throw new RuntimeException("已然被实例化一次，不能在实例化");
        }
        isCreate = true;
    }

    /**
     * 防止克隆
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return instance;
    }

    /**
     * 防止序列化破环
     *
     * @return
     */
    private Object readResolve() {
        return instance;
    }
}
